import SwiftUI
import CoreLocation

// MARK: - 苹果地理编码示例视图

struct AppleGeocodingView: View {
    @State private var addressString: String = "正在获取地址..."
    @State private var isLoading: Bool = false
    @State private var selectedCoordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 39.9161, longitude: 116.4037)
    
    private let geocodingService = AppleGeocodingService.shared
    
    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                // 标题
                Text("苹果地理编码示例")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                    .padding(.top)
                
                Divider()
                
                // 坐标输入区域
                VStack(alignment: .leading, spacing: 10) {
                    Text("输入坐标:")
                        .font(.headline)
                    
                    HStack {
                        Text("纬度:")
                            .font(.subheadline)
                        TextField("纬度", value: $selectedCoordinate.latitude, format: .number)
                            .textFieldStyle(RoundedBorderTextFieldStyle())
                            .keyboardType(.decimalPad)
                    }
                    
                    HStack {
                        Text("经度:")
                            .font(.subheadline)
                        TextField("经度", value: $selectedCoordinate.longitude, format: .number)
                            .textFieldStyle(RoundedBorderTextFieldStyle())
                            .keyboardType(.decimalPad)
                    }
                }
                .padding()
                .background(Color.gray.opacity(0.1))
                .cornerRadius(10)
                
                // 预设坐标按钮
                VStack(spacing: 10) {
                    Text("预设坐标:")
                        .font(.headline)
                    
                    HStack(spacing: 10) {
                        Button("北京王府井") {
                            selectedCoordinate = CLLocationCoordinate2D(latitude: 39.9161, longitude: 116.4037)
                        }
                        .buttonStyle(.bordered)
                        
                        Button("上海外滩") {
                            selectedCoordinate = CLLocationCoordinate2D(latitude: 31.2304, longitude: 121.4737)
                        }
                        .buttonStyle(.bordered)
                        
                        Button("广州塔") {
                            selectedCoordinate = CLLocationCoordinate2D(latitude: 23.1066, longitude: 113.3245)
                        }
                        .buttonStyle(.bordered)
                    }
                }
                
                // 结果显示区域
                VStack(alignment: .leading, spacing: 10) {
                    Text("解析结果:")
                        .font(.headline)
                    
                    ScrollView {
                        Text(addressString)
                            .font(.body)
                            .padding()
                            .frame(maxWidth: .infinity, alignment: .leading)
                            .background(Color.gray.opacity(0.1))
                            .cornerRadius(10)
                    }
                    .frame(maxHeight: 200)
                }
                
                // 操作按钮
                VStack(spacing: 15) {
                    Button(action: {
                        fetchAddress()
                    }) {
                        HStack {
                            if isLoading {
                                ProgressView()
                                    .scaleEffect(0.8)
                            }
                            Text(isLoading ? "正在解析..." : "开始解析")
                        }
                        .frame(maxWidth: .infinity)
                        .padding()
                        .background(isLoading ? Color.gray : Color.blue)
                        .foregroundColor(.white)
                        .cornerRadius(10)
                    }
                    .disabled(isLoading)
                    
                    Button("清除结果") {
                        addressString = "正在获取地址..."
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.orange)
                    .foregroundColor(.white)
                    .cornerRadius(10)
                }
                
                Spacer()
            }
            .padding()
            .navigationTitle("苹果地理编码")
            .navigationBarTitleDisplayMode(.inline)
        }
        .onAppear {
            fetchAddress()
        }
    }
    
    // MARK: - 核心功能：获取地址的方法
    
    private func fetchAddress() {
        isLoading = true
        addressString = "正在解析，请稍候..."
        
        geocodingService.fetchAddressInfo(
            latitude: selectedCoordinate.latitude,
            longitude: selectedCoordinate.longitude
        ) { addressInfo in
            isLoading = false
            
            guard let addressInfo = addressInfo else {
                addressString = "解析失败: 无法获取地址信息"
                return
            }
            
            // 构建详细的地址信息显示
            var details: [String] = []
            
            if let name = addressInfo.name, !name.isEmpty {
                details.append("📍 名称: \(name)")
            }
            
            if let thoroughfare = addressInfo.thoroughfare, !thoroughfare.isEmpty {
                details.append("🛣️ 街道: \(thoroughfare)")
            }
            
            if let subThoroughfare = addressInfo.subThoroughfare, !subThoroughfare.isEmpty {
                details.append("🏘️ 子街道: \(subThoroughfare)")
            }
            
            if let subLocality = addressInfo.subLocality, !subLocality.isEmpty {
                details.append("🏘️ 子区域: \(subLocality)")
            }
            
            if let locality = addressInfo.locality, !locality.isEmpty {
                details.append("🏙️ 城市: \(locality)")
            }
            
            if let administrativeArea = addressInfo.administrativeArea, !administrativeArea.isEmpty {
                details.append("🗺️ 省份: \(administrativeArea)")
            }
            
            if let postalCode = addressInfo.postalCode, !postalCode.isEmpty {
                details.append("📮 邮编: \(postalCode)")
            }
            
            if let country = addressInfo.country, !country.isEmpty {
                details.append("🇨🇳 国家: \(country)")
            }
            
            if let isoCountryCode = addressInfo.isoCountryCode, !isoCountryCode.isEmpty {
                details.append("🌍 国家代码: \(isoCountryCode)")
            }
            
            // 添加格式化地址
            details.append("\n📋 完整地址: \(addressInfo.formattedAddress)")
            
            addressString = details.isEmpty ? "未找到有效的地址信息" : details.joined(separator: "\n")
        }
    }
}

// MARK: - 预览

struct AppleGeocodingView_Previews: PreviewProvider {
    static var previews: some View {
        AppleGeocodingView()
    }
} 